// pages/Goods/Commit/index.js
var common = require("../../../public.js")
const config = require('../../../config.js')
const app = getApp();
Page({
    data: {
        onlyCompanyDiscount:0,// 企业券折扣多少钱
        onlyGoldDiscount:0,// 金豆折扣多少钱
        onlyVipDiscount:0, // 会员折扣多少钱 ，例如总价100，比率为0.01的话，就抵扣99元
        hasBuy: false, //已购买
        cardVipShow: false,
        memeberSelect: false,
        currentVipDiscount: '',
        currentCompanySelectIndex:-1,//
        currentCardSelectIndex: -1, // <=0,不使用会员折扣或者不是会员，>0使用会员折扣并且是会员 
        cardVipJson: '', // 当前选中的会员折扣json
        nianList: [],
        cardListSelectShow: false,// 会员卡折扣弹框
        goldToal: '', // 金豆数量   可计算修改
        goldToalTwo: '', // 金豆数量  固定不变
      skuPrice:'',
        skuId:'',
        special:'',
        radio: '1',
        isFyApp: config.isFyApp,
        selectedAddr: false,
        active: 0, //默认选中配送方式  开始根据下标0开始
        userInfo: [],
        itemId: 0,
        storeId: 0,
        cityBenefitItemFlag: false, // 市级惠民
        benefitItemFlag: false, // 省级惠民1
        storeInfo: '', //店铺详情
        goodsInfo: '', //商品详情
        totalPostType: [], //根据店铺返回的共有多少个配送方式
        postType: 1, //邮寄方式
        count: 1, //数量
        price: 0, //单价
        storePriceTwo: 0, // 商品总价 不混合其他价格(券,金豆等)
        storePrice: 0, //商品总价  从item/info取到的price，后期会涉及到和 优惠券/金豆等等的计算，所以是包括和各种优惠计算后的价格 
        totalMoney: 0, // 最后支付总价
        StoPrice: 0, // 企业券优惠总额 例如10， 优惠10元
        benefitPrice: 0, // 惠民券优惠价格
        postage: 0, //邮费默认值
        pickUpSelfName: '', // 提货人姓名
        pickUpSelfPhone: '', // 提货人手机
        hasSelectPAmount: 0, // 始终为0
        hasSelectCityPAmount: 0, // 始终为0
        receiverName: '',
        receiverMobile: '',
        receiverAddress: '',
        bottomBtnContent: '确认提交',
        cityCouponNo: '', //市级优惠卷编号
        canCommit: false,
        invitationCode: '',
        remark: '',
        loadingCount: 0, // 记录当前请求的个数，当不为0时，会显示加载提示
        loadingSuccessCount: 0,
        //1是微信支付 2银联支付
        goldValue: '',
        showGold: false,
        counts: 0, //金豆数量
        valueGold: 0,
        Stops: false,
        cardId: '',
        max: 0,
        arrText: [

            {
                isSelect: false,
                name: '暂不使用金豆'
            },
            {
                isSelect: false,
                name: '抵扣￥1.00最高可使用100金豆'
            },
            {
                isSelect: false,
                name: '自定义使用金豆数量'
            },
        ],
        currentGoldSelectIndex: -1, // 当前选中了某个金豆抵扣选项
        goldBean: true,
        inputNum: 0,
        value: '',
        showStoreCoupons: false,
        comL: [], //企业券
        benefitListtop: [], //惠民券
        benefitListbottom: [], //惠民券
        showBenefitCoupons: false,
        benefitPricTop: 0,
        flag: true, //控制开关
        flags: true, //控制开关
        storePriceAddress: -1,
        inputPrice: 0,
        discountCoupons: [], //惠民叠加券

    },
    // 企业券确定
    ComPany_submit() {
        console.log('comL--', this.data.comL,'==currentCompanySelectIndex==', this.data.currentCompanySelectIndex)
        console.log("打印却确定", this.data.totalPreferential)
        this.setData({
            showStoreCoupons: false,
            onlyCompanyDiscount:this.data.comL[this.data.currentCompanySelectIndex].discountsMoney
        },()=>{
            console.log('价格哈--', this.data.onlyCompanyDiscount)
            this.excludeUseFunc(1)
        })
   

        
        
        // console.log(this.data.comL, "dkdddiokdjd")
    },
    onBenefitCouponosClose() { //惠民券关闭
        this.clearFn()
    },

    //清空
    clearFn() {
        // 关闭
        // 叠加券上部
        var totalTop = 0;
        for (var i = 0; i < this.data.benefitListtop.length; i++) {
            var item = this.data.benefitListtop[i]
            if (item.isSelect) {
                totalTop = totalTop + item.discountsMoney
            }
        }
        // 叠加券底部
        var totalBottom = 0;
        for (var i = 0; i < this.data.benefitListbottom.length; i++) {
            var item = this.data.benefitListbottom[i]
            if (item.isSelect) {
                totalBottom = totalBottom + item.discountsMoney
            }
        }
        for (var i = 0; i < this.data.benefitListbottom.length; i++) {
            this.data.benefitListbottom[i].isSelect = false
        }
        for (var i = 0; i < this.data.benefitListtop.length; i++) {
            this.data.benefitListtop[i].isSelect = false
        }
        this.setData({

            benefitListtop: this.data.benefitListtop,
            benefitListbottom: this.data.benefitListbottom,
            benefitPrice: 0,
            showBenefitCoupons: false,
            flag: true,
            storePrice: this.data.storePrice + totalTop + totalBottom,

        })
    },
    // 单选
    click_benefit(e) {
        var that = this
        let {
            index,
            item
        } = e.currentTarget.dataset
        // that.data.goodsInfo.price
        if (that.data.goodsInfo.price * that.data.count < item.exceedMoney && that.data.flag && that.data.benefitListtop.length != 1) {
            common.showToast('商品总额不能低于满减金额')
            return
        }
        if (that.data.flag && that.data.goodsInfo.price * that.data.count < item.exceedMoney && that.data.benefitListtop.length == 1) {
            common.showToast('商品总额不能低于满减金额')
            return
        }
        // 选中的前提下
        if (!that.data.flag && item.isSelect != true) {
            common.showToast('此为单选，请先取消选中')
            return
        }
        for (var i = 0; i < this.data.benefitListtop.length; i++) {
            if (i == index) {
                this.data.benefitListtop[i].isSelect = !this.data.benefitListtop[i].isSelect
            } else {
                this.data.benefitListtop[i].isSelect = false
            }
        }
        if (!item.isSelect) {
            var benefitPricTop = this.data.benefitPrice + item.discountsMoney //单选的优惠金额
            var benefitPrice = this.data.benefitPrice + item.discountsMoney
            var storePrice = this.data.storePrice - item.discountsMoney
            console.log('啊啊啊啊','benefitPricTop','--', benefitPrice,'--',storePrice)
        } else {
            var benefitPricTop = this.data.benefitPrice - item.discountsMoney //单选的优惠金额
            var benefitPrice = this.data.benefitPrice - item.discountsMoney
            var storePrice = this.data.storePrice + item.discountsMoney
            console.log('嘿嘿嘿','benefitPricTop','--', benefitPrice,'--',storePrice)
        }
        console.log('benefitPricTop---', benefitPricTop)
        console.log('benefitPrice---', benefitPrice)
        console.log('storePrice---', storePrice)
        this.setData({
            benefitListtop: this.data.benefitListtop,
            benefitPricTop, //单选优惠券
            benefitPrice,
            storePrice
        }, () => {
            if (this.data.benefitListtop.findIndex(targrt => targrt.isSelect == true) == -1) {
                that.setData({
                    flag: true
                })
            } else {
                that.setData({
                    flag: false
                })
            }
        })
    },
    // 叠加券
    benefit_coup(e) {
        var that = this
        let {
            index,
            item
        } = e.currentTarget.dataset
        console.log(item, "itemitemitem")
        if (that.data.goodsInfo.price * this.data.count < item.exceedMoney && !item.isSelect) {
            common.showToast('商品总额不能低于满减金额')
            return
        }

        for (var i = 0; i < this.data.benefitListbottom.length; i++) {
            if (i == index) {
                this.data.benefitListbottom[i].isSelect = !this.data.benefitListbottom[i].isSelect
            }
            // console.log(this.data.benefitListbottom,"oojjjlllll")
        }
        if (!item.isSelect) {
            var benefitPricTop = this.data.benefitPrice + item.discountsMoney //单选的优惠金额
            var benefitPrice = this.data.benefitPrice + item.discountsMoney
            var storePrice = this.data.storePrice - item.discountsMoney
        } else {
            var benefitPricTop = this.data.benefitPrice - item.discountsMoney //单选的优惠金额
            var benefitPrice = this.data.benefitPrice - item.discountsMoney
            var storePrice = this.data.storePrice + item.discountsMoney
        }
        that.setData({
            benefitListbottom: this.data.benefitListbottom,
            benefitPricTop, //单选优惠券
            benefitPrice,
            storePrice
            // storePrice:storePrice>0 ? storePrice : 0.01
        })
    },
    onStoreCouponosClose() {
        this.compnayClose()
    },
    compnayClose() {
        console.log(this.data.comL, "关闭关闭")
        var companyTotal = 0
        for (var i = 0; i < this.data.comL.length; i++) {
            var item = this.data.comL[i]
            if (item.isSelect) {
                companyTotal = companyTotal + this.data.comL[i].discountsMoney
            }
        }
        for (var i = 0; i < this.data.comL.length; i++) {
            this.data.comL[i].isSelect = false
        }
        this.setData({
            storePrice: this.data.storePrice + companyTotal,
            StoPrice: 0,
            comL: this.data.comL,
            flags: true,
            showStoreCoupons: false,
            componyobjs: ''
        })
    },

    // 店铺优惠券线上券
    copuStoreList() {
        var that = this
        var tempJson = {
            storeId: that.data.storeId,
            couponType: 1, //1线上券，2线下券
            token: that.data.token,
            userId: that.data.userInfo.id
        };
        common.wxRequest("/discountCoupon/getMyCouponForStoreByType", "post", tempJson, 'application/x-www-form-urlencoded', function (res) {
            console.log(res);
            if (res.status == 200) {
                var arr = []
                for (var i = 0; i < res.data.length; i++) {
                    res.data[i].beginTime = common.dateFormat('yyyy-MM-dd', res.data[i].beginTime)
                    res.data[i].finishTime = common.dateFormat('yyyy-MM-dd', res.data[i].finishTime)
                    res.data[i].isSelect = false
                    // console.log( res.data[i].exceedMoney)
                    if (that.data.storePrice - res.data[i].exceedMoney > 0) {
                        console.log(res.data[i].exceedMoney)
                        arr.unshift(res.data[i])
                    } else {
                        arr.push(res.data[i])
                    }
                }
                that.setData({
                    comL: arr
                }, () => {
                    that.setData({
                        showStoreCoupons: true
                    })
                })
            }
        });
    },
    // 惠民券
    copuBenifitList() {
        var that = this
        var tempJson = {
            userId: that.data.userInfo.id,
            token: that.data.token,
            itemId: that.data.itemId,
            buyNums: that.data.count,

        };
        common.wxRequest("/order/getUserCityDiscountCoupon", "post", tempJson, 'application/x-www-form-urlencoded', function (res) {
            console.log(res);
            if (res.status == 200) {
                that.setData({
                    coupToTal: res.data,
                })
                var arr = [];
                for (var i = 0; i < res.data.length; i++) {
                    res.data[i].receiveTime = common.dateFormat('yyyy-MM-dd', res.data[i].receiveTime)
                    res.data[i].endTime = common.dateFormat('yyyy-MM-dd', res.data[i].endTime)
                    res.data[i].isSelect = false
                    if (that.data.storePrice - res.data[i].exceedMoney > 0) {

                        arr.unshift(res.data[i])
                    } else {
                        arr.push(res.data[i])
                    }
                }
                var res = arr
                var benefitListtop = res.filter(item => item.isComposit == 1 || item.isComposit == null)
                var benefitListbottom = res.filter(item => item.isComposit !== 1 && item.isComposit !== null)
                console.log('benefitListtop--', benefitListtop)
                that.setData({

                    benefitListtop,
                    benefitListbottom
                }, () => {
                    that.setData({
                        showBenefitCoupons: true
                    })
                })
            } else {
                common.showToast(res.msg)
            }
        });
    },
    click_company(e) {
        var that = this
        let {
            index,
            item
        } = e.currentTarget.dataset
        console.log('item---', item)
        if (that.data.goodsInfo.price * that.data.count < item.exceedMoney && that.data.flags && that.data.comL.length != 1) {
            common.showToast('商品总额不能低于满减金额')
            return
        }
        if (that.data.flags && that.data.goodsInfo.price * that.data.count < item.exceedMoney && that.data.comL.length == 1) {
            common.showToast('商品总额不能低于满减金额')
            return
        }
        if (!that.data.flags && item.isSelect != true) {
            common.showToast('此为单选，请先取消选中')
            return
        }
        for (var i = 0; i < this.data.comL.length; i++) {
            if (i == index) {
                this.data.comL[i].isSelect = !this.data.comL[i].isSelect
            } else {
                this.data.comL[i].isSelect = false
            }
        }
        if (!item.isSelect) { // 选中
            var StoPrice = this.data.StoPrice + item.discountsMoney //单选的优惠金额
            console.log('aa处理后----aa', StoPrice)
            // console.log(this.data.storePrice,"StoPriceStoPriceStoPrice")
            var storePrice = this.data.storePrice.toFixed(2) - StoPrice
            this.setData({
                currentCompanySelectIndex:index
            },()=>{
                console.log('222急急急---', this.data.currentCompanySelectIndex)
            })


        } else { // 未选中

            var StoPrice = this.data.StoPrice - item.discountsMoney //单选的优惠金额
            console.log('bb处理后----bb', StoPrice)
            var storePrice = this.data.storePrice + this.data.StoPrice
            this.setData({
                currentCompanySelectIndex:-1
            },()=>{
                console.log('4444急急急---', this.data.currentCompanySelectIndex)
            })
        }
        console.log(storePrice, "storePricestorePrice")
        this.setData({
            StoPrice,
            // storePrice:storePrice > 0 ? storePrice : 0.01,
            storePrice,
            comL: this.data.comL
        }, () => {
            console.log(this.data.comL)
            var inde = this.data.comL.findIndex(t => t.isSelect == true)
            console.log(inde, "ddd")
            var coupObj = inde != -1 ? this.data.comL[inde] : ''
            console.log(coupObj, "coupObjcoupObj")
            that.setData({
                componyobjs: coupObj
            })
            if (this.data.comL.findIndex(targrt => targrt.isSelect == true) == -1) {
                that.setData({
                    flags: true
                })

            } else {
                that.setData({
                    flags: false
                })
            }
        })

       

    },
    // 企业券
    companyVoucherList() {
        console.log('企业圈弹框')
        this.compnayClose()
        this.copuStoreList()
    },
    // 提交
    submit_clicks() {
        this.setData({
            showGold: false,
            // counts:this.data.currentGoldSelectIndex === 0?0:(this.data.currentGoldSelectIndex ===1?this.data.counts:),
            counts:this.data.currentGoldSelectIndex === 0?0:this.data.counts,
            onlyGoldDiscount:this.data.currentGoldSelectIndex === 0?0:(this.data.currentGoldSelectIndex === 1?  this.data.onlyGoldDiscount:this.data.counts / 100)
        },()=>{
            this.excludeUseFunc(2);
        })

    },
    // 金豆弹框
    goldFlag() {
        this.setData({
            showGold: true
        })
    },
    clcik_index(e) {
        console.log(e, 11111)
        var that = this
        let {
            index,
            item
        } = e.currentTarget.dataset

        var storePrice = this.data.storePrice
        if (index== 0) {// 不使用金豆
            storePrice = parseFloat(this.data.storePrice) + (this.data.counts / 100) * (app.globalData.discount ? app.globalData.discount : 1) //总价格

            this.setData({
                counts: 0
            })
        } else if (index == 1) {// 最高可用金豆
            if (this.data.arrText[1].isSelect) {
                return
            }
            this.setData({
                counts: this.data.goldToalTwo,
                value: 0
            }, () => {
                if ((this.data.storePrice) - (this.data.counts / 100) < 0) {
                    common.showToast('抵扣金额不能超过付款额')
                    this.setData({
                        counts: 0,
                        value: 0
                    })
                    return
                }
                // storePrice = (this.data.storePrice) - (this.data.counts / 100) * (app.globalData.discount ? app.globalData.discount : 1) //总价格
                console.log("想喝---", storePrice, "ffffppppp")
                this.setData({
                    // storePrice,
                    onlyGoldDiscount: this.toFixedPrice(this.data.counts / 100),
                    inputPrice: storePrice
                })
            })
            this.setData({
                storePrice,
                inputPrice: storePrice
            })
            // }

        } else if (index == 2) { // 自定义使用金豆
            storePrice = parseFloat(this.data.storePrice) + (this.data.counts / 100) * (app.globalData.discount ? app.globalData.discount : 1) //总价格

            this.setData({
                // counts: 0,
                value: 0
            })
            this.setData({
                storePrice,
                inputPrice: storePrice
            })
        }
        // StoPrice企业券  benefitPrice惠民券
        // var storePricess

        if ((this.data.storePrice) - (this.data.counts / 100) < 0) {
            common.showToast('抵扣金额不能超过付款额')
            return
        } else {
           this.dealGoldListFunc(index)
        }

    },
    dealGoldListFunc(index){
        for (var i = 0; i < this.data.arrText.length; i++) {
            if (index == i) {
                this.data.arrText[i].isSelect = true
            } else {
                this.data.arrText[i].isSelect = false
            }
        }
        this.setData({
            arrText: this.data.arrText,
            currentGoldSelectIndex: index,
            goldBean: false,
        })
        
    },

    dealCardListFunc(index){
        for (var i = 0; i < this.data.nianList.length; i++) {
            if (index == i) {
                this.data.nianList[i].isSelect = true

            } else {

                this.data.nianList[i].isSelect = false


            }
        }
        this.setData({
            currentCardSelectIndex: index,
            nianList: this.data.nianList
        })
    },

    // 金豆弹框确定
    submitClose() {

        this.setData({
            showGold: false
        })
    },
    //购买数量  计算数量金额加
    goldNumChange(e) {
        var that = this;
        console.log(e.detail, "lfllll")
        var num;
        if (e.detail == '') {
            num = 0
        } else {
            num = parseInt(e.detail)
        }
        that.setData({
            counts: num, //金豆数量
            inputNum: num,
        }, () => {
            console.log(this.data.goldToalTwo) //金豆总数量
            if (this.data.inputPrice < this.data.inputNum / 100) {
                common.showToast("抵扣不能超过付款金额")
                that.setData({
                    counts: 0, //金豆数量
                    value: 0, //金豆数量
                    storePrice: that.data.inputPrice
                })
                return
            } else if (this.data.goldToalTwo <= this.data.inputNum) {
                this.setData({
                    value: this.data.goldToalTwo,
                    inputNum: this.data.goldToalTwo,
                    counts: this.data.goldToalTwo
                }, () => {
                    common.showToast('已超过最高抵用')
                })
            } else if (this.data.inputNum < 0) {
                this.setData({
                    value: 0,
                    inputNum: 0,
                    counts: 0
                }, () => {
                    // common.showToast('已超过最高抵用')
                })
            }
            var goldToal = ((that.data.userAssets.totalMoney) - that.data.counts).toFixed(2)
            var storePrice = parseFloat(this.data.inputPrice.toFixed(2)) - (this.data.counts / 100) * (app.globalData.discount ? app.globalData.discount : 1) //总价格
            that.setData({
                storePrice,
                goldToal
            })
            // }
        })
    },
    // 地址列表
    addressList() {
        const that = this
        const tempJson = {
            userId: that.data.userInfo.id,
            token: that.data.token
        }
        common.post('/user/ship/list', tempJson, function (res) {
            if (res.status === 200) {
                console.log(res, "55555")
                if (Array.isArray(res.data) && res.data.length) {
                    let obj = res.data.find((v) => v.isDefault == 1 || res[0])
                    that.setData({
                        receiverName: obj.receiverName,
                        receiverMobile: obj.receiverMobile,
                        receiverAddress: obj.receiverAddress,
                        selectedAddr: true,
                        isDefault: obj.isDefault
                    })
                }
            } else {
                common.showRequestErrMsg(res)

            }
        })
    },
    getUserAssets() { // 获取余额
        const that = this
        const tempJson = {
            userId: that.data.userInfo.id,
            token: that.data.token
        }
        common.post('/userDeposit/getUserAssetsGold', tempJson, function (res) {
            if (res.status === 200) {
                that.setData({
                    userAssets: res.data,
                    goldToal: res.data.totalMoney,
                    goldToalTwo: res.data.totalMoney
                }, () => {
                    var totalM = (parseFloat(that.data.goodsInfo.price) * app.globalData.discount * that.data.count)
                    var gtotalNumber = (that.data.userAssets.totalMoney) //金豆总钱
                    // 计算最大可使用量
                    if (gtotalNumber < totalM) { // 金豆数量 小于 金额的max =金豆
                        that.setData({
                            max: (gtotalNumber)
                        })
                    } else if (gtotalNumber > totalM) { // 金豆数量 大于 金额的max =金豆
                        that.setData({
                            max: (totalM * 100)
                        })
                    } else { // 金豆数量 等于 金额的max =金豆
                        that.setData({
                            max: (gtotalNumber)
                        })
                    }
                })
            } else {
                common.showRequestErrMsg(res)
                that.setData({
                    userAssets: res.data
                })
            }
        })
    },
    onClose() {
        var that = this
        // var storePrice = (parseFloat(that.data.goodsInfo.price) - that.data.counts / 100 * app.globalData.discount).toFixed(2) //总价格
        this.setData({
            showGold: false, //  金豆抵扣 弹框关闭
            cardListSelectShow: false // 会员折扣弹框关闭
            // storePrice
        });
        this.dealCardListFunc(0)
    },
    // 金豆选择
    goldBean(event) {
        this.setData({
            goldValue: '1',
        });
    },
    onChanges(event) {
        this.setData({
            radio: event.detail,
        });
    },
    onClick(event) {
        const {
            name
        } = event.currentTarget.dataset;
        this.setData({
            radio: name,
        });
    },
    // 惠民叠加券
    clcik_dieJia() {
        var filterArrBottom = this.data.benefitListbottom.filter(x => x.isSelect == true)
        var filterArrTop = this.data.benefitListtop.filter(x => x.isSelect == true)
        var filterArrBottomKey = []
        var obj = {}
        for (var j = 0; j < filterArrBottom.length; j++) {
            obj = {
                'couponNo': filterArrBottom[j].couponNo
            }
            filterArrBottomKey.push(obj)
            console.log(filterArrBottomKey, "84556655444555")
        }
        // var bottomArr = []
        for (var i = 0; i < filterArrBottom.length; i++) {
            if (filterArrBottom[i].isComposit == 3 && filterArrBottom.length == 1 && (filterArrTop.length == 0 || !filterArrTop)) {
                common.showToast('叠加券不可以单独使用')
                return
            }

        }
        var youHui = this.data.totalPreferential + this.data.benefitPrice
        this.setData({
            cityCouponNo: filterArrTop.length > 0 ? filterArrTop[0].couponNo : '', //惠民券上部分
            discountCoupons: filterArrBottomKey,
            showBenefitCoupons: false,
            totalPreferential: youHui
        },()=>{
            this.excludeUseFunc(4)
        })
    },

    onShow() {
        console.log("onShowjinlailejjjj")
    },
    onLoad: function (options) {
        const that = this
        console.log(options, "666666666666666666")
        if (options.invitationCode) { // 是vip商品填写邀请码
            that.setData({
                invitationCode: that.options.invitationCode
            })
        }

        common.getLocalUserInfo(function (success, data) {
            if (success) {
                that.setData({
                    userInfo: data.user,
                    token: data.token,
                    openid: data.openid,
                    itemId: options.itemId,
                    storeId: options.storeId,
                    special:options.special?options.special:'',
                    // itemId: '7336',  //毛笔
                    // storeId: '14',
                    // itemId: 21523,  //一个花店
                    // storeId: 5004,
                    // itemId: 11711, //一个花店
                    // storeId: 2532,
                    pickUpSelfName: data.user.realName,
                    pickUpSelfPhone: data.user.phone,
                    cardId: app.globalData.cardId,
                    skuId:options.skuId,
                    skuPrice:options.skuPrice,
                }, function () {
                    console.log('cardId---',this.data.cardId);
                    console.log('productprice---',this.data.productprice);
                    console.log('discount---',this.data.discount);
       
                    this.setData({
                        storePriceAddress: options.storePrice ? parseFloat(options.storePrice) : -1
                    }, () => {
                        that.getGoodsDes() //查询商品详情信息
                        that.getShopDes() //店铺详情

                    })


                    if (!that.data.selectedAddr) {
                        that.addressList() //地址列表
                    }

                    if (options.selectedAddr) {
                        // 已经选择地址的逻辑，当前逻辑是从选择地址列表返回
                        that.setData({
                            selectedAddr: options.selectedAddr,
                            receiverName: options.receiverName,
                            receiverMobile: options.receiverMobile,
                            receiverAddress: options.receiverAddress,
                        })
                    } else {
                        // 默认进入 - 未选择地址，从下单页面进入
                        getApp().getLocation(function (data) {
                            that.data.lon = data.longitude
                            that.data.lat = data.latitude
                            that.setData({
                                xpoint: data.longitude,
                                ypoint: data.latitude
                            }, function () {
                                that.dealPostMethodsFunc();
                                
                            })
                        })
                    }
                })
            }
        }, true)
    },
    dealPostMethodsFunc(){
        if(this.data.special){
            this.setData({
                totalPostType:[],
                postType: 2,
                postage: 0,
                // postage: 100,
                loadingSuccessCount: that.data.loadingSuccessCount + 1
            }, function () {
                // that.selectComponent('#vanTabs').resize()
            })
        }else{
            this.getPostType() //根据位置查询店铺配送方式
        }
       
    },
    inputEvent(e) { },
    //查询商品详情信息
    getGoodsDes() {
        const that = this
        let tempJson = {
            itemId: that.data.itemId
        }
        that.setData({
            loadingCount: that.data.loadingCount + 1,
            loadingSuccessCount: that.data.loadingSuccessCount - 1
        }, function () {
            common.post('/item/info', tempJson, function (res) {
                that.cardsList() // 年卡列表
                console.log('1122--',res);
                if (res.status === 200) {
                    var storeprice;
                    console.log(app.globalData.discount, "app.globalData.discountapp.globalData.discount")
                    if (that.data.storePriceAddress == -1) {
                        console.log('AAAAA');
                        // storeprice = app.globalData.cardId ? (app.globalData.productprice) : (res.data.price * app.globalData.discount)
                        storeprice = that.data.skuPrice?that.data.skuPrice:res.data.price
                        // 会员卡    嘻嘻哈哈哈- 0 --- 0.0 ===== 280 GGGGGG 0.0
                        // 正常    嘻嘻哈哈哈- 105 --- 1 ===== 105 GGGGGG 1
                        console.log('嘻嘻哈哈哈-',storeprice,'---',app.globalData.discount,'=====',res.data.price,'GGGGGG',app.globalData.discount)
                        that.getUserAssets()
                    } else {
                        console.log('BBBBBB');
                        storeprice = that.data.storePriceAddress
                        console.log('dddfgf-',storeprice)
                    }
                    console.log('33444');
                    that.setData({
                        goodsInfo: res.data,
                   
                        cityBenefitItemFlag: res.data.cityBenefitItemFlag,
                        benefitItemFlag: res.data.benefitItemFlag,
                        storePrice: parseFloat(storeprice),
                        // storePriceTwo: app.globalData.cardId ? (app.globalData.productprice) : (res.data.price * app.globalData.discount),
                        storePriceTwo:that.data.skuPrice?that.data.skuPrice:res.data.price,
                        price: res.data.price,
                        loadingSuccessCount: that.data.loadingSuccessCount + 1
                        // totalMoney:
                    }, () => {
                        // var isNum =     //是整数，则返回true，否则返回false
                        if (typeof that.data.storePrice == 'number' && that.data.storePrice % 1 == 0) {
                            that.setData({
                                isNum: true
                            })
                        } else {
                            that.setData({
                                isNum: false
                            })
                        }

                    })
                } else {
                    common.showRequestErrMsg(res)
                }
            }, function () {
                that.setData({
                    loadingCount: that.data.loadingCount - 1
                })
            })
        })
    },
    //查询店铺信息
    getShopDes() {
        var that = this
        let tempJson = {
            storeId: that.data.storeId
        }
        this.setData({
            loadingCount: this.data.loadingCount + 1,
            loadingSuccessCount: that.data.loadingSuccessCount - 1
        })
        common.post('/store/info', tempJson, function (res) {
            if (res.status === 200) {
                that.setData({
                    storeInfo: res.data,
                    loadingSuccessCount: that.data.loadingSuccessCount + 1
                })
            } else {
                common.showRequestErrMsg(res)
            }
        }, function () {
            that.setData({
                loadingCount: that.data.loadingCount - 1
            })
        })
    },
    //查询店铺配送方式
    getPostType: function () {
        var that = this
        var tempJson = {
            storeId: that.data.storeId,
            userId: that.data.userInfo.id,
            xpoint: that.data.xpoint,
            ypoint: that.data.ypoint
        }
        this.setData({
            loadingCount: this.data.loadingCount + 1,
            loadingSuccessCount: that.data.loadingSuccessCount - 1
        })
        common.post('/store/getStorePostTypeForBuyUser', tempJson, function (res) {
            if (res.status === 200) {
                that.setData({
                    totalPostType: res.data,
                    postType: res.data[0].feeType,// 3快递 2到店自提
                    postage: that.data.special?0:(res.data[0].price ? res.data[0].price : 0),
                    // postage: 100,
                    loadingSuccessCount: that.data.loadingSuccessCount + 1
                }, function () {
                    // that.selectComponent('#vanTabs').resize()
                })
            } else {
                common.showRequestErrMsg(res)
            }
        }, function () {
            that.setData({
                loadingCount: that.data.loadingCount - 1
            })
        })
    },
    //点击选中的配送方式
    onChangePostType(event) {
        console.log('event--',event);
        let that = this
        if (!event.detail.index) {
            this.addressList()
        }
        that.setData({
            selectedAddr: false,
            receiverName: '',
            receiverMobile: '',
            receiverAddress: '',
        })
        let feeType = event.detail.name
        that.data.totalPostType.map((item, index) => {
            if (item.feeType == feeType) {
                console.log("yunxing", item.price)
                that.setData({
                    postage: item.price,
                    postType: item.feeType
                })
            }
        })
    },
    //购买数量  计算数量金额
    onNumChange(e) {
      // skuPrice
      console.log('e.detail---',e.detail);
      console.log('app.globalData.discount---',app.globalData.discount);
        var that = this;
        // if (app.globalData.cardId) {
        //     var storePrice = parseFloat(app.globalData.productprice) * e.detail
        // } else {
        //     var storePrice = parseFloat(that.data.goodsInfo.price) * e.detail * app.globalData.discount
        // }
        var storePrice = that.data.skuPrice?that.data.skuPrice*e.detail:parseFloat(that.data.goodsInfo.price) * e.detail ;
        that.setData({
            count: e.detail,
            storePrice: storePrice,
            storePriceTwo: storePrice
        })
    },
    voucherPayFunc() {
        var that = this
        let payment = that.data.storePrice + that.data.postage - (that.data.hasSelectPAmount || that.data.hasSelectCityPAmount)

        var tempJson = {
            token: that.data.token,
            payType: 0,
            invitationCode: that.data.invitationCode,
            list: [{
                order: {
                    payment: payment.toFixed(2),
                    userId: that.data.userInfo.id,
                    postFee: that.data.postage,
                    buyerMessage: that.data.remark,
                    remark: that.data.remark,
                    buyerNick: that.data.userInfo.userName,
                    storeId: that.data.storeId,
                    postType: that.data.postType, //1—商城配送; 2到店自提 3快递
                    orderType: 1, //商品订单1，活动订单2
                    userDiscountCouponId: that.data.componyobjs.udcId
                },
                items: [{
                    skuId:that.data.skuId,
                    itemId: that.data.itemId,
                    num: that.data.count,
                    title: that.data.goodsInfo.title,
                    price: that.data.goodsInfo.price,
                    totalFee: that.data.count * that.data.goodsInfo.price,
                    picPath: that.data.userInfo.image,
                }],
                ship: {
                    receiverName: that.data.receiverName || that.data.pickUpSelfName,
                    receiverPhone: '', //可以为空
                    receiverMobile: that.data.receiverMobile || that.data.pickUpSelfPhone,
                    receiverAddress: that.data.receiverAddress,
                    receiverZip: ''
                }
            }]
        };
        tempJson.list[0].order.couponNo = that.data.hasSelectPNo
        tempJson.list[0].order.discountMoney = that.data.hasSelectPAmount
        tempJson.list[0].order.payment = tempJson.list[0].order.payment - parseInt(that.data.hasSelectPAmount);
        if (that.data.radio == 1) {
            // var url = '/order/createBenefitOrder'
            var url = '/order/createChinaumsOrderForH5Sku'
        } else if (that.data.radio == 2) { //银联支付
            var url = '/order/createChinaumsOrderForH5Sku'
        }
        console.log('创建订单json---', tempJson)
        common.postJson(url, tempJson, function (ret) {
            if (ret.status == 200) {
             
                    ret.data[0].order.payment + '&payBenefitOrderNo=' +
                    ret.data[0].order.orderNo + '&payBenefitOrderId=' + ret.data[0].order.id
                wx.navigateTo({
                    url: '/packageA/pages/Goods/benefit/benefitPay/index?payBenefitMoney=' +ret.data[0].order.payment + '&payBenefitOrderNo=' + ret.data[0].order.orderNo +
                        '&payBenefitOrderId=' + ret.data[0].order.id + "&fromSmallProgramm=true"
                })
                return
            } else {
                common.showToast({
                    title: ret.msg,
                    icon: 'none'
                })
            }
        })
    },
    normalPayFunc() {
        console.log("测试数据666666")
        this.setData({
            loadingCount: this.data.loadingCount + 1
        })
        const that = this
        // const payment = that.data.storePrice + that.data.postage - (that.data.hasSelectPAmount || that.data.hasSelectCityPAmount) // 实付金额

        const payment = that.data.storePriceTwo - that.data.onlyVipDiscount - that.data.onlyGoldDiscount - that.data.onlyCompanyDiscount// 实付金额


        const tempJson = {
            token: that.data.token,
            invitationCode: that.data.invitationCode || '',
            payType: 0,
            cardId: that.data.cardId,
            list: [{
                order: {
                    cardDiscountAmount:that.data.onlyVipDiscount,
                    payment: payment.toFixed(2),
                    userId: that.data.userInfo.id,
                    postFee: that.data.postage, //邮费
                    buyerMessage: that.data.remark,
                    remark: that.data.remark,
                    buyerNick: that.data.userInfo.userName,
                    storeId: that.data.storeId,
                    postType: that.data.postType, //1—商城配送; 2到店自提 3快递
                    orderType: 1, //商品订单1，活动订单2
                    cityCouponNo: that.data.cityCouponNo,
                    goldPrice: that.data.counts, //金豆抵扣
                    userDiscountCouponId: that.data.componyobjs ? that.data.componyobjs.udcId : '', //企业券线上
                    discountCoupons: that.data.discountCoupons
                    // discountCoupons:
                },
                items: [{
                    skuId:that.data.skuId,
                    itemId: that.data.itemId,
                    num: that.data.count,
                    title: that.data.goodsInfo.title,
                    price: that.data.goodsInfo.price,
                    totalFee: that.data.count * that.data.goodsInfo.price,
                    picPath: that.data.goodsInfo.image,
                }],
                ship: {
                    receiverName: that.data.receiverName || that.data.pickUpSelfName,
                    receiverPhone: '', //可以为空
                    receiverMobile: that.data.receiverMobile || that.data.pickUpSelfPhone,
                    receiverAddress: that.data.receiverAddress,
                    receiverZip: ''
                },
            }]
        };

        //创建订单
        // if (that.data.radio == 1) {
        //   var url = '/order/create'
        // var url = '/order/createChinaumsOrder'
        // } else if (that.data.radio == 2) {

        // console.log(that.data.cardId, "that.data.cardIdthat.data.cardId")
        // if (that.data.cardId) {  //会员卡商品
        //     var url = '/order/create'
        // } else {
            var url = '/order/createChinaumsOrderForH5Sku'
        // }
console.log('tempJson---',tempJson);
        //  return;
        common.postJson(url, tempJson, function (ret) {
            if (ret.status == 200) {
             
                if (payment == 0 && that.data.postage == 0 && !that.data.StoPrice && !that.data.benefitPrice) {
                    wx.showToast({
                        title: '支付成功',
                        icon: 'none',
                        success: res => {
                            setTimeout(() => {
                                if (that.data.cardId) {
                                    wx.navigateTo({
                                        url: '/pages/ScenicArea/NianCardOrder/index?titles=1',
                                        // url:'pages/scanForPay/index'
                                    })
                                } else {
                                    wx.navigateTo({
                                        url: '/packageA/pages/Goods/goodsOrder/goodsOrderList/index?type=1',
                                    })
                                }
                            }, 1000)
                        }
                    })
                    return
                }
                // var tempJson = {
                //     userId: that.data.userInfo.id,
                //     token: that.data.token,
                //     orderId: ret.data[0].order.id,
                //     openid: that.data.openid,
                // }

                var tempJson = {
                    userId: that.data.userInfo.id,
                    token: that.data.token,
                    orderId: ret.data[0].order.id,
                    xcxOpenid: that.data.openid,
                }
                that.setData({
                    loadingCount: that.data.loadingCount + 1
                })
                // if (that.data.radio == 1) {

                // var urls = '/wxxcxPayForGoods'
                // } else if (that.data.radio == 2) {
                // if (that.data.cardId) {
                    var urls = '/wxxcxPayForGoods'
                // } else {
                    // var urls = '/wxxcxPayGoodsForFYPlatformChinaUms'
                // }


                // }

                common.wxPayRequest(urls, that.data.radio == 1 ? tempJson : tempJsons, function (res) {
                    console.log(res, "lilili")
                    if (res.status !== 200) {
                        common.showRequestErrMsg(res)
                    } else {
                        //微信支付
                        wx.requestPayment({
                            'timeStamp': res.data.timeStamp,
                            'nonceStr': res.data.nonceStr,
                            'package': res.data.package,
                            'signType': res.data.signType,
                            'paySign': res.data.paySign,
                            'success': function (res) {
                                common.showToast('支付成功', 'success')
                                if (that.data.cardId != '') {
                                    wx.navigateTo({
                                        url: '/pages/ScenicArea/NianCardOrder/index?titles=1',
                                    })
                                } else {
                                    wx.navigateBack({
                                        delta: 1
                                    })
                                }

                            },
                            'fail': function (res) {
                                if (that.data.cardId != '') {
                                    wx.navigateTo({
                                        url: '/pages/ScenicArea/NianCardOrder/index?titles=1',
                                    })
                                } else {
                                    wx.redirectTo({
                                        url: '/packageA/pages/Goods/goodsOrder/goodsOrderList/index?type=1',
                                    })
                                }

                                if (res.errMsg === 'requestPayment:fail cancel') { } else {
                                    common.showToast(res.errMsg)
                                }
                            }
                        })
                    }
                }, function () {
                    that.setData({
                        loadingCount: that.data.loadingCount - 1
                    })
                })
            } else {
                common.showRequestErrMsg(ret)
            }
        }, function () {
            that.setData({
                loadingCount: that.data.loadingCount - 1
            })
        })
    },
    commit: common.throttleFunc(function (e) {
        if (this.data.loadingSuccessCount !== 0) {
            // 存在加载失败的接口，不进行订单提交
            // 全部加载成功loadingSuccessCount值为0
            return
        }
        const that = this
        // 自提方式，验证收货人和手机号
        if (that.data.goodsInfo.typeId == 2||that.data.special) {
            that.data.postType = 2//1—商城配送; 2到店自提 3快递
            that.data.postage = 0
        }
        console.log(that.data.postType)
        if (that.data.postType === '2' || that.data.postType === 2) {//1—商城配送; 2到店自提 3快递
            const name = that.data.pickUpSelfName
            if (common.isEmptyString(name)) {
                common.showToast('请输入提货人姓名')
                return
            } else if (common.isEmptyString(that.data.pickUpSelfPhone)) {
                common.showToast('请输入手机号码')
                return
            }
        }
        if (that.data.selectedAddr || that.data.postType == 2) {//1—商城配送; 2到店自提 3快递
            if (that.data.hasSelectPAmount) { // 省级券 应该是惠民券
                console.log('已选中惠民券');
                that.voucherPayFunc();
            } else { // 没券和市级券
                console.log('不用券||市券');
                that.normalPayFunc();
            }
        } else {
            common.showToast('您还未添加任何地址~')
        }
    }, 2000),


    jumpVoucherList() {
        console.log("ooojjjjh")
        this.clearFn()
        this.copuBenifitList()

        //   wx.navigateTo({
        //     url: '/packageA/pages/Goods/benefit/benefitVoucher/index?num=' +
        //       this.data.count + "&itemId=" +
        //       this.data.itemId +
        //       '&cityBenefitItemFlag=' +
        //       this.data.cityBenefitItemFlag +
        //       '&benefitItemFlag=' + this.data.benefitItemFlag +
        //       '&storeId=' + this.data.storeId
        //   })
    },

    cardListSelectFunc() {
        this.setData({
            cardListSelectShow: true
        })
    },
    cardsList() {
        var that = this

        common.get('/userAnnualCard/getUserAnnualCardListForOneStore', {
            storeId: that.data.storeId,
            userId: that.data.userInfo.id,
            token: that.data.token
        }, res => {
            if (res.status === 200) {
         
                that.setData({
                    nianList: res.data
                }, () => {
                    if (that.data.nianList.length) {
                        var json = {
                            name: '暂不使用',
                            isSelect: false,
                            validTime: '666',
                            payRate: 1,
                        };


                        that.data.nianList.unshift(json)
                        var min = Math.min.apply(Math, res.data.map(function (o) {
                            return o.payRate;
                        }))
                        console.log("最小的z折扣---", min); // 2
                        for (var i = 0; i < that.data.nianList.length; i++) {
                            if (parseFloat(that.data.nianList[i].payRate) == min) {
                                console.log('fff====');
                                that.data.nianList[i].isSelect = true;
                                that.setData({
                                    cardVipJson: that.data.nianList[i],
                                    currentCardSelectIndex: i,
                                    currentVipDiscount: min,
                                    onlyVipDiscount:this.toFixedPrice((this.data.storePriceTwo)*(100-min*100)/100),





                                })
                            }
                        }
                        that.setData({
                            nianList: that.data.nianList,
                            memeberSelect: true,
                            hasBuy: true,
                            cardVipShow: true,

                        }, () => {
                            console.log('nianList===', that.data.nianList);
                        })
                    }else{
                        that.setData({
                            nianList: [],

                        }, () => {
                            console.log('nianList===', that.data.nianList);
                        })
                    }
                })
            } else {
                common.showRequestErrMsg(res)
            }
        })
    },
    cardListSelectFunc() {
        this.setData({
            cardListSelectShow: true
        })
    },
    card_item_index(e) {
        var that = this
        let {
            index,
            item
        } = e.currentTarget.dataset
        console.log('index---', index, '-----item---', item);
        this.dealCardListFunc(index)
    },
    dealCardListFunc(index){
        for (var i = 0; i < this.data.nianList.length; i++) {
            if (index == i) {
                this.data.nianList[i].isSelect = true

            } else {

                this.data.nianList[i].isSelect = false


            }
        }
        this.setData({
            currentCardSelectIndex: index,
            nianList: this.data.nianList
        })
    },
    toFixedPrice (x) { // 格式化价格保留两位
        var f_x = parseFloat(x);
        if (isNaN(f_x)) {
          return 0.00;
        }
        var f_x = Math.round(x * 100) / 100;
        var s_x = f_x.toString();
        var pos_decimal = s_x.indexOf('.');
        if (pos_decimal < 0) {
          pos_decimal = s_x.length;
          s_x += '.';
        }
        while (s_x.length <= pos_decimal + 2) {
          s_x += '0';
        }
        return s_x;
      
      },
    submit_vip_discount_sure() {


        console.log('nianList=---', this.data.nianList);
        console.log('会员卡索引=---', this.data.currentCardSelectIndex);
        this.setData({
            cardVipJson: this.data.nianList[this.data.currentCardSelectIndex],
            currentVipDiscount: this.data.nianList[this.data.currentCardSelectIndex].payRate,
            cardListSelectShow: false,
        },()=>{
            this.excludeUseFunc(3)
        })
    },
    excludeUseFunc(type) {
        console.log('type---', type)
        // 1优惠券 2金豆 3会员权益   

        // 
        if(type === 1){
            console.log('选择了企业券')
            this.setData({
                benefitPrice: 0,// 惠民券清0
                currentGoldSelectIndex:-1, // 金豆抵扣弹框，未选中任何选项
                counts:0, // 金豆为0
                onlyGoldDiscount: 0,// 金豆折扣
                currentCardSelectIndex: -1, // <=0,不使用会员折扣或者不是会员，>0使用会员折扣并且是会员 
                onlyVipDiscount:0
            })
            //  让金豆抵扣选框都不选中
            this.dealGoldListFunc(-1)
            // 让会员折扣的选框都不选中
            this.dealCardListFunc(-1)
        }
        if(type === 2){
            console.log('选择了金豆')
            this.setData({
                benefitPrice: 0,// 惠民券清0
                currentCardSelectIndex: -1, // <=0,不使用会员折扣或者不是会员，>0使用会员折扣并且是会员 
                onlyVipDiscount:0,
                componyobjs:{} // 清空已选企业券信息
            })
            // 让会员折扣的选框都不选中
            this.dealCardListFunc(-1)
        }
        if(type === 3){
            console.log('选择了会员权益')
            this.setData({
                benefitPrice: 0,// 惠民券清0
                currentGoldSelectIndex:-1, // 金豆抵扣弹框，未选中任何选项
                counts:0, // 金豆为0
                onlyGoldDiscount: 0,// 金豆折扣,
                currentCompanySelectIndex: -1,// 企业券变为未选中
                onlyCompanyDiscount:0,// 企业券折扣
                onlyVipDiscount:this.toFixedPrice((this.data.storePriceTwo)*(100-this.data.currentVipDiscount*100)/100),
                componyobjs:{} // 清空已选企业券信息
            },()=>{
                console.log('fff000', this.data.onlyVipDiscount)
            })
            //  让金豆抵扣选框都不选中
            this.dealGoldListFunc(-1)
        }

        if(type === 4){
            console.log('选择了惠民券')
            this.setData({
                currentGoldSelectIndex:-1, // 金豆抵扣弹框，未选中任何选项
                counts:0, // 金豆为0
                onlyGoldDiscount: 0,// 金豆折扣
                currentCardSelectIndex: -1, // <=0,不使用会员折扣或者不是会员，>0使用会员折扣并且是会员 
                onlyVipDiscount:0,
                componyobjs:{} // 清空已选企业券信息
            })
            //  让金豆抵扣选框都不选中
            this.dealGoldListFunc(-1)
            // 让会员折扣的选框都不选中
            this.dealCardListFunc(-1)
        }
    }
})